package com.crm.service.before_sale.impl;

import com.crm.dao.before_sale.CompetitorDAO;
import com.crm.exception.ServiceException;
import com.crm.pojo.*;
import com.crm.service.before_sale.CompetitorService;
import com.crm.vo.CompetitorVO;
import com.crm.vo.OfferDetailsVO;
import com.crm.vo.PlanDetailsVO;
import com.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.sql.rowset.serial.SerialException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class CompetitorServiceimpl implements CompetitorService {
    @Autowired
    private CompetitorDAO competitorDAO;

    public void addCompetitor(){

    }

    /**
     * 获取竞争对手分页数据
     * @param curpage
     * @param rows
     * @return
     */
    @Override
    public List<CompetitorVO> getCompetitorList(int curpage, int rows) {

        try {
            PageRequest pageRequest = new PageRequest(curpage-1,rows);
            List<CompetitorVO> list = competitorDAO.queryCompetitorsByPage(pageRequest);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }


    }

    /**
     * 获取竞争对手数量
     * @return
     */
    @Override
    public Long getCompetitorExistTotal() {

        try {
            return competitorDAO.getCompetitorExistCount();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /**
     * 删除竞争对手
     * @param comId
     */
    @Override
    public Result deleteCompetitor(Long comId) throws ServiceException{

        try {
            competitorDAO.deleteCompetitorById(comId);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(e);
        }
    }



    @Override
    public List<String> findAllSaleChanceNameByChId(Long chId) {
        try {
            return competitorDAO.findAllSaleChanceNameByChId(chId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    @Override
    public List<ClientInfo> findAllClientInfoName() {
        return competitorDAO.findAllClientInfoName();
    }

    @Override
    public List<SaleChance> findAllSaleChanceName() {
        try {
            return competitorDAO.findAllSaleChanceName();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /**
     * 添加竞争对手
     * @param comName
     * @param comPower
     * @param comProduct
     * @param comPrice
     * @param coping
     * @param remarks
     * @param chId
     * @param cid
     * @return
     * @throws ServiceException
     */
    @Override
    public Result addCompetitor(String comName, String comPower, String comProduct, BigDecimal comPrice, String coping,
                                String remarks,  BigDecimal chId, BigDecimal cid)throws ServiceException {
        try {
            List<Competitor> list = competitorDAO.queryCompetitorsByComName(comName);
            if (list != null && list.size()!= 0){
                return new Result("该对手已存在！");
            }else {
                Competitor competitor = new Competitor();
                competitor.setComName(comName);
                competitor.setComPower(comPower);
                competitor.setComProduct(comProduct);
                competitor.setComPrice(comPrice);
                competitor.setCoping(coping);
                competitor.setRemarks(remarks);
                competitor.setCompetitorIsDel("否");
                competitor.setChanceId(chId);
                competitor.setClientId(cid);

                competitorDAO.save(competitor);
                return Result.SUCCESS;

            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("添加失败！");
        }

    }

    /**
     * 编辑
     * @param competitor
     * @return
     */
    @Override
    public Result editCompetitor(Competitor competitor) {
        try {
            competitorDAO.save(competitor);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("Sorry,编辑失败！");
        }
    }

    /**
     * 分页展示竞争对手列表
     * @param competitor
     * @param curpage
     * @param pagesize
     * @return
     */
    @Override
    public List<Competitor> showCompetitorList(Competitor competitor, int curpage, int pagesize) {
        Assert.notNull(competitor);
        PageRequest pageRequest = new PageRequest(curpage-1,pagesize, Sort.Direction.DESC,"comId");
        @SuppressWarnings("unchecked")
        Page page = competitorDAO.findAll(new Specification<Competitor>() {
            @Override
            public Predicate toPredicate(Root<Competitor> root, CriteriaQuery<?> argl, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                //根据以下条件查询
                //1.公司名称
                if(!StringUtils.isEmpty(competitor.getComName())){
                    list.add(cb.like(root.get("comName").as(String.class),"%" + competitor.getComName() + "%"));
                }
                //2.竞争能力
                if(!StringUtils.isEmpty(competitor.getComPower())){
                    list.add(cb.like(root.get("comPower").as(String.class),"%" + competitor.getComPower() + "%"));
                }
                //没有被删除
                list.add(cb.notLike(root.get("competitorIsDel").as(String.class), "是"));

                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },pageRequest);
        List<Competitor> list = page.getContent();
        return list;
    }

    /**
     * 获取竞争对手总数量
     * @param competitor
     * @return
     */
    @Override
    public Long getCompetitorCount(Competitor competitor) {
        Assert.notNull(competitor);
        Long toatal = competitorDAO.count(new Specification<Competitor>() {
            @Override
            public Predicate toPredicate(Root<Competitor> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                //根据以下条件查询
                //1.公司名称
                if(!StringUtils.isEmpty(competitor.getComName())){
                    list.add(cb.like(root.get("comName").as(String.class),"%" + competitor.getComName() + "%"));
                }
                //2.竞争能力
                if(!StringUtils.isEmpty(competitor.getComPower())){
                    list.add(cb.like(root.get("comPower").as(String.class),"%" + competitor.getComPower() + "%"));
                }
                //没有被删除
                list.add(cb.notLike(root.get("competitorIsDel").as(String.class), "是"));

                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        return toatal;
    }

    /**
     * 根据客户编号查询销售机会
     * @param clientId
     * @return
     */
    @Override
    public List<SaleChance> getSaleChanceListByClientId(Long clientId)throws ServiceException {
        try {
            return competitorDAO.getSaleChnceListByClientId(new BigDecimal(clientId.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /**
     * 根据客户编号查询客户需求
     * @param clientId
     * @return
     */
    @Override
    public List<ClientNeed> getClientNeedListByClientId(Long clientId)throws ServiceException {
        try {
            return competitorDAO.getClientNeedListByClientId(new BigDecimal(clientId.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /**
     * 根据客户编号查询解决方案
     * @param clientId
     * @return
     */
    @Override
    public List<Scheme> getSchemeListByClientId(Long clientId) throws ServiceException{
        try {
            return competitorDAO.getSchemeListByClientId(clientId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /**
     * 根据客户编号查询竞争对手
     * @param clientId
     * @return
     */
    @Override
    public List<Competitor> getCompetitorListByClientId(Long clientId) throws ServiceException{
        try {
            return competitorDAO.getCompetitorListByClientId(new BigDecimal(clientId.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /**
     * 根据客户编号查询计划及计划明细
     * @param clientId
     * @return
     */
    @Override
    public List<PlanDetailsVO> getPlanDetailsVOListByClientId(Long clientId) throws ServiceException{
        try {
            return competitorDAO.getSalePlanDetailsVOListByClientId(new BigDecimal(clientId.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /**
     * 根据客户编号查询报价及报价明细
     * @param clientId
     * @return
     */
    @Override
    public List<OfferDetailsVO> getOfferDetailVOListByClientId(Long clientId) {
        return competitorDAO.getOfferDetailVOListByClientId(new BigDecimal(clientId));
    }


}
